var isAdmin = false;
var userRoles = null;
var routeOper = false;
Ext.define('cfWeb.controller.accountSetting.AccountSettingController',{
	extend : 'Ext.app.Controller',
	views : ['cfWeb.view.accountSetting.AccountSettingWindow',
			 'accountSetting.CloudManageView',
			 'accountSetting.DomainManageView',
			 'accountSetting.OrgManageView',
			 'accountSetting.RouteManageView',
			 'accountSetting.SpaceManageView',
			 'accountSetting.UserManageView',
			 'accountSetting.RunEnvManageView',
			 'accountSetting.UserAddUser',
			 'accountSetting.OrgAddUserWindow',
			 'accountSetting.SpaceAddUserWindow',
			 'accountSetting.DomainAddUserWindow',
			 'accountSetting.AuthOrgUserWindow',
			 'accountSetting.BuildpackManageView',
			 'accountSetting.AddBuildpackWindow',
			 'accountSetting.RouteAddWindow',
			 'accountSetting.RouteAppEditWindow',
			 'accountSetting.OrgEditWindow',
			 'accountSetting.SpaceEditWindow',
			 'cfWeb.cfWebComponent.NavView',
			 'cfWeb.view.accountSetting.SettingWindow',
			 'cfWeb.view.util.HomeTabView'
			],
	stores :['accountSetting.OrgStore',
			 'accountSetting.SpaceStore',
			 'accountSetting.UserStore',
			 'accountSetting.DomainStore',
			 'accountSetting.RouteStore',
			 'accountSetting.AuthUserStore',
			 'accountSetting.OrgRoleStore',
			 'accountSetting.SpaceRoleStore',
			 'accountSetting.AppNameStore',
			 'accountSetting.TestStore',
			 'cfWeb.store.util.dashboard.RouteUsedStore'
			],
	settingWindow : undefined,
	orgName: undefined,
	spaceName: undefined,
	host:undefined,
	domainName:undefined,
	oldApps:undefined,
	rowStore:undefined,
	rowIndex:undefined,
	init : function(){
		this.control({
			'addBuildpackWindow button[itemId=add]' :{
				click : this.addBuildpack
			},
			'BuildpackManageView' :{
				render : this.buildpackGridRender
			},
			'BuildpackManageView button[itemId=addBuildpack]' :{
				click : this.addBuildpackWindow
			},
			'orgManageView' :{
				afterrender: this.orgGridAfterrender
			},
			'orgManageView button[itemId=addUser]' :{
				click : this.orgAddUser
			},
			'orgManageView actioncolumn[text=用户授权]' :{
				click : this.authOrgUser
			},
			'authOrgUserWindow combobox[itemId=orgType]' :{
				change : this.orgTypeChange
			},
			'authOrgUserWindow itemselector[itemId=orgSelector]' :{
				render : this.orgSelectRender
			},
			'authOrgUserWindow combobox[itemId=spaceType]' :{
				change : this.spaceTypeChange
			},
			'authOrgUserWindow button[itemId=updateRole]' :{
				click : this.updateRole
			},
			'authOrgUserWindow button[itemId=cancel]':{
				click : this.authCancelButton
			},
			'orgAddUserWindow':{
				afterrender:this.quotaLoad
			},
			'orgAddUserWindow button[itemId=add]' :{
				click : this.orgAddButton
			},
			'orgAddUserWindow button[itemId=cancel]':{
				click : this.orgAddCancelButton
			},
			'routeManageView' :{
				afterrender: this.routeGridRender
			},
//			'routeManageView combobox[itemId=space_combobox]' :{
//				change: this.routerChangeSpace
//			},
			'routeManageView combobox[itemId=org]':{
				change:this.routerSpaceComboxChoose
			},
			'routeManageView combobox[itemId=space]':{
				change:this.routerChangeSpace
			},
			'routeManageView button': {
				click: this.routerAdd
			},
			'routeManageView actioncolumn[itemId=editRouter]' : {
				click: this.routeEdit
			},
			
			'routeAddWindow button[itemId=addRoute]':{
				click:this.routeAddButton
			},
			
			'routeAppEditView button[itemId=editRouterSubmit]':{
				click:this.editRouterSubmit
			},
			
			'routeAppEditView':{
				close:this.afterRouteEditClose
			},hidden : true,
			'spaceManageView' :{
				render : this.spaceGridRender
			},
			'spaceManageView button[itemId=addSpaceUser]' :{
				click : this.spaceAddUser
			},
			'spaceManageView combobox[itemId=org]' :{
				change : this.spaceChangeOrg
			},
			'spaceAddUserWindow button[itemId=add]' :{
				click : this.spaceAddButton
			},
			'spaceAddUserWindow button[itemId=cancel]' :{
				click : this.spaceCancelButton
			},
			'userManageView' : {
				show : this.userGridRender
			},
			'userManageView actioncolumn' : {
				click : this.operatorClick
			},
			'userManageView button[itemId=addUser]':{
				click : this.userAddUser
			},
			'userAddUser button[itemId=add]' :{
				click : this.userAddButton
			},
			'userAddUser button[itemId=cancel]':{
				click : this.userCancelButton
			},
			'domainManageView' :{
				render : this.domainGridRender
			},
			'domainManageView button[itemId=addDomain]' :{
				click : this.domainAddUser
			},		
			'domainManageView combobox[itemId=org]' :{
				change : this.domainChangeOrg
			},
			'domainAddUserWindow combobox[itemId=property]' :{
				change : this.domainChangeProperty
			},
			'domainAddUserWindow button[itemId=add]' :{
				click : this.domainAddButton
			},
			'domainAddUserWindow button[itemId=cancel]' :{
				click : this.domainCancelButton
			},
			'orgEditWindow':{
				afterrender:this.quotaLoad
			},
			'orgEditWindow button[itemId=confirm]' :{
				click : this.orgEditConfirmButton
			},
			'orgEditWindow button[itemId=cancel]' :{
				click : this.orgEditCancelButton
			},
			'spaceEditWindow button[itemId=confirm]' :{
				click : this.spaceEditConfirmButton
			},
			'spaceEditWindow button[itemId=cancel]':{
				click : this.spaceEditCancelButton
			},
			'routeAddWindow button[itemId=cancel]':{
				click:this.routeCancelButton
			},
			'routeAppEditView button[itemId=cancel]':{
				click:this.editRouterCancel
			},
			'SettingWindow':{
				beforerender:this.renderWin,
				close : this.routeFresh
			}
		});
	},
	quotaLoad:function(win){
		var combobox=win.down('combobox[name=quota]');
		combobox.getStore().load({
			callback:function(records){
				if(!win.edit&&records.length>0){
					combobox.setValue(records[0].get("guid"));
				}
			}
		});
	},
	clickTest : function(){
		alert("you have click the button");
	},
	
	addBuildpackWindow : function(me){
		var addPackWin=Ext.create('cfWeb.view.accountSetting.AddBuildpackWindow');
		addPackWin.packManageView=me.up('BuildpackManageView');
		console.log(me.up('BuildpackManageView'));
		addPackWin.show();
	},

	addBuildpack : function(me){
		var packManageView=me.up('addBuildpackWindow').packManageView;
		var form=me.ownerCt.ownerCt;
		var name=form.items.items[0].getValue();
		var file=form.items.items[1].getValue();
		console.log(form.items.items[1].getValue());
		if(name==''||name==undefined){
			Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.buildpackWindow.nameEmp);
		}else if(file==''||file==undefined){
			Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.buildpackWindow.fileEmp);
		}
		else{
			var waitWindow=Ext.MessageBox.show({title : cfWebLang.Util.uploading,closable: false,cls:'style-cfLoading'});
			form.submit({
	  			url : 'rest/buildpack/addBuildpack',
	  			method : 'POST',
	  			success : function(resp){
	  				waitWindow.close();
	  				Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Util.AddSuccess);
	  				form.ownerCt.hide();
	  				packManageView.items.items[0].getStore().load();
	  			},
	  			failure : function(response) {
	  				waitWindow.close();
	  				if(response.status=="401"){
    	               Ext.Msg.show({
    	                  title: cfWebLang.Util.Tip,
    	                  id:'firstWin',
    	                  msg: cfWebLang.Main.SessionOverdue,
    	                  width: 250,
    	                  buttons: Ext.MessageBox.OK,
    	                  fn: function(){  
                             parent.location.href = '/zwycf/login.html';    
                          },
                          cls:'overtimeWin'
    	              });
                      return;
                    } 
                   if(response.timedout){  
                      Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                         return;
                   }
					var error = Ext.JSON.decode(response.responseText);
				    if(error.data!=null&&error.data.source==1){
					     Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				    }else{
					     Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				    }
				}
	  		});
		}
	},
	buildpackGridRender : function(me){
		var buildpackGrid=me.down('grid[itemId=buildpackManageView]');
		console.log(buildpackGrid);
		var store=buildpackGrid.getStore();
		store.load();
		buildpackGrid.setVisible(true);
	},
	orgTypeChange:function(combo){
		var win=combo.up("authOrgUserWindow");
		var org=combo.getValue();
		var userId=win.userId;
		var orgSelector=win.down("#orgSelector");
		orgSelector.reset();
		console.log(userId);
		Ext.Ajax.request({
			url : 'rest/user/userOrgRole',
			method : 'GET',
			async:false,
			params :{
				orgName : org,
				userId : userId,
			},
			root : 'data',
			success : function(resp){
				console.log(resp);
				console.log("succe1ss");
				var select=Ext.JSON.decode(resp.responseText);
				var data=select.data;
				win.orgRole=[];
				for(var i=0;i<data.length;i++){
					console.log(data[i]);
					win.orgRole.push(data[i]);
				}
				orgSelector.setValue(data);
				
			},
			failure : function(response) {
				if(response.status=="401"){
    	             Ext.Msg.show({
    	               title: cfWebLang.Util.Tip,
    	               id:'firstWin',
    	               msg: cfWebLang.Main.SessionOverdue,
    	               width: 250,
    	               buttons: Ext.MessageBox.OK,
    	               fn: function(){  
                          parent.location.href = '/zwycf/login.html';    
                       },
                       cls:'overtimeWin'
    	             });
                     return;
                 } 
                 if(response.timedout){  
                    Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                       return;
                 }
				var error = Ext.JSON.decode(response.responseText);
				if(error.data!=null&&error.data.source==1){
					Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				}else{
					Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				}	
			}
		});
		var spaceCombo=win.down('#spaceType');
		spaceCombo.getStore().getProxy().url='rest/space/list?orgName='+org+'&userId='+userId;
		spaceCombo.getStore().load({
			callback:function(records){
				console.log(records);
				if(records.length!=0){
					   spaceCombo.setValue(records[0].data.name);
				}else{
				       spaceCombo.setValue('');
				}
			}
		});
	},
	orgSelectRender : function(me){
		var win=me.up("authOrgUserWindow");
		var naview=Ext.ComponentQuery.query('navView')[0];
		var currentOrgSpace=naview.getOrgSpace();
		var comboboxOrg = win.down('#orgType');
		comboboxOrg.setValue(currentOrgSpace.org)
		var org=comboboxOrg.getValue();
		var userId=win.userId;
		var orgSelector=win.down("#orgSelector");
		Ext.Ajax.request({
			url : 'rest/user/userOrgRole',
			method : 'GET',
			params :{
				orgName : org,
				userId : userId,
			},
			root : 'data',
			success : function(resp){
				console.log("succe1ss");
				var select=Ext.JSON.decode(resp.responseText);
				var data=select.data;
				for(var i=0;i<data.length;i++){
					console.log(data[i]);
					win.orgRole.push(data[i]);
				}
				orgSelector.setValue(data);
			},
			failure : function(response) {
				if(response.status=="401"){
    	             Ext.Msg.show({
    	               title: cfWebLang.Util.Tip,
    	               id:'firstWin',
    	               msg: cfWebLang.Main.SessionOverdue,
    	               width: 250,
    	               buttons: Ext.MessageBox.OK,
    	               fn: function(){  
                          parent.location.href = '/zwycf/login.html';    
                       },
                       cls:'overtimeWin'
    	             });
                     return;
                 } 
                 if(response.timedout){  
                    Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                       return;
                 }
				var error = Ext.JSON.decode(response.responseText);
				if(error.data!=null&&error.data.source==1){
					Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				}else{
					 Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				}	
			}
		});
		var comboboxSpace = win.down('#spaceType');
		comboboxSpace.setValue(currentOrgSpace.space);
		comboboxSpace.getStore().getProxy().url='rest/space/list?orgName='+org+'&userId='+userId;
		comboboxSpace.getStore().load();
		var space=comboboxSpace.getValue();
		var spaceSelector=win.down("#spaceSelector");
		Ext.Ajax.request({
			url : 'rest/user/userSpaceRole',
			method : 'GET',
			params :{
				spaceName : space,
				userId : userId,
			},
			root : 'data',
			success : function(resp){
				console.log(resp);
				console.log("succe1ss");
				var select=Ext.JSON.decode(resp.responseText);
				var data=select.data;
				for(var i=0;i<data.length;i++){
					console.log(data[i]);
					win.spaceRole.push(data[i]);
				}
				spaceSelector.setValue(data);
			},
			failure : function(response) {
				if(response.status=="401"){
    	             Ext.Msg.show({
    	               title: cfWebLang.Util.Tip,
    	               id:'firstWin',
    	               msg: cfWebLang.Main.SessionOverdue,
    	               width: 250,
    	               buttons: Ext.MessageBox.OK,
    	               fn: function(){  
                          parent.location.href = '/zwycf/login.html';    
                       },
                       cls:'overtimeWin'
    	             });
                     return;
                 } 
                 if(response.timedout){  
                     Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                        return;
                 }
				var error = Ext.JSON.decode(response.responseText);
				if(error.data!=null&&error.data.source==1){
				   Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				}else{
				    Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				}	
			}
		});
	},
	spaceTypeChange:function(combo){
		//alert("render");
		var win=combo.up("authOrgUserWindow");
		var space=combo.getValue();
		var userId=win.userId;
		var spaceSelector=win.down("#spaceSelector");
		spaceSelector.reset();
		Ext.Ajax.request({
			url : 'rest/user/userSpaceRole',
			method : 'GET',
			params :{
				spaceName : space,
				userId : userId,
			},
			root : 'data',
			success : function(resp){
				console.log(resp);
				console.log("succe1ss");
				var select=Ext.JSON.decode(resp.responseText);
				var data=select.data;
				win.spaceRole=[];
				for(var i=0;i<data.length;i++){
					console.log(data[i]);		
					win.spaceRole.push(data[i]);
				}
				spaceSelector.setValue(data);
			},
			failure : function(response) {
				if(response.status=="401"){
    	             Ext.Msg.show({
    	               title: cfWebLang.Util.Tip,
    	               id:'firstWin',
    	               msg: cfWebLang.Main.SessionOverdue,
    	               width: 250,
    	               buttons: Ext.MessageBox.OK,
    	               fn: function(){  
                          parent.location.href = '/zwycf/login.html';    
                       },
                       cls:'overtimeWin'
    	             });
                     return;
                 } 
                 if(response.timedout){  
                    Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                       return;
                 }
				var error = Ext.JSON.decode(response.responseText);
				if(error.data!=null&&error.data.source==1){
				   Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				}else{
				    Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				}	
			}
		});
	},
	updateRole : function(me){
		console.log('updateRole');
		var win=me.up('authOrgUserWindow');
		var userId=win.userId;
		var spaceSelector=win.down("#spaceSelector");
		var orgSelector=win.down("#orgSelector");
		var orgCombo=win.down('#orgType');
		var spaceCombo=win.down('#spaceType');
		var org=orgCombo.getValue();
		var space=spaceCombo.getValue();
		console.log(userId+'  '+spaceSelector.value+'   '+orgSelector.value);
		var orgRole=win.orgRole;
		var spaceRole=win.spaceRole;
		console.log(userId+'  '+orgRole+'  '+spaceRole);
		var aorgRoles=this.arr_dive(orgSelector.value, orgRole);console.log(aorgRoles);
		var dorgRoles=this.arr_dive(orgRole ,orgSelector.value);console.log(dorgRoles);
		var aspaceRoles=this.arr_dive(spaceSelector.value, spaceRole);console.log(aspaceRoles);
		var dspaceRoles=this.arr_dive(spaceRole, spaceSelector.value);console.log(dspaceRoles);
		Ext.Ajax.request({
			url : 'rest/user/updateUserRole',
			method : 'post',
			params :{
				orgName : org,
				aorgRoles : aorgRoles,
				dorgRoles : dorgRoles,
				spaceName : space,
				aspaceRoles : aspaceRoles,
				dspaceRoles : dspaceRoles,
				userId : userId,
			},
			success : function(resp){
				console.log(resp);
				console.log("success");
				win.orgRole=orgSelector.value;
		        win.spaceRole=spaceSelector.value;
		        Ext.Msg.alert('提示', '用户授权成功');
		        win.close();
			},
			failure : function(response) {
				if(response.status=="401"){
    	             Ext.Msg.show({
    	               title: cfWebLang.Util.Tip,
    	               id:'firstWin',
    	               msg: cfWebLang.Main.SessionOverdue,
    	               width: 250,
    	               buttons: Ext.MessageBox.OK,
    	               fn: function(){  
                          parent.location.href = '/zwycf/login.html';    
                       },
                       cls:'overtimeWin'
    	             });
                     return;
                 } 
                 if(response.timedout){  
                    Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                       return;
                 }
				var error = Ext.JSON.decode(response.responseText);
				if(error.data!=null&&error.data.source==1){
				   Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				}else{
				    Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				}
			}
		});
		
	},
	arr_dive : function(aArr,bArr){   //第一个数组减去第二个数组
	    if(bArr.length==0){return aArr}
	    var diff=[];
	    var str=bArr.join("&quot;&quot;");
	    for(var e in aArr){
	        if(str.indexOf(aArr[e])==-1){
	            diff.push(aArr[e]);
	        }
	    }
	    return diff;
	},
	operatorClick:function(view, cell, row, col, e){
		var tooltip=e.target.className;
		if(tooltip.indexOf('auth_user_selector')>0){
			var rec = view.getStore().getAt(row);
			var userId = rec.get('id');
			var window = this.getView('accountSetting.AuthOrgUserWindow').create();
			console.log(window);
			window.setTitle(cfWebLang.Util.UserAuth);
			window.userId=userId;
			window.show();
		}
	},
	orgGridAfterrender : function(me){
		var orgGrid=me.down('grid[itemId=orgManagePanel]');
		var store=orgGrid.getStore();
		console.log(store.data);
		console.log(store.data.items);
		
		store.load();
		console.log("helloworld");
		var window=me.up('SettingWindow');
		var currentOrg = window.currentSpace;
		var orgButton = me.down('button');
	},
	authOrgUser : function(view, cell, row, col, e){
		console.log("second authuser");
	/*	var rec = view.getStore().getAt(row);
		var name = rec.get('name');
		var window = this.getView('accountSetting.AuthOrgUserWindow').create();
		window.setTitle(name);
		alert(window.title);
		window.show();*/
	},
	
	authChangeRole : function(me,value){
		console.log(me);
		console.log(value);
		var view=me.up('window');
		console.log(view);
		var grid=view.down('itemselector[itemId=authOrgUserSelector]');
		var orgName = view.title;
		var store=grid.getStore();
		console.log(store);
		store.load({
			url : 'rest/user/orgUser',
			params : {
				orgName : orgName,
				roleType : value
			}
		});
		grid.setVisible(true);
	},
	authCancelButton : function(me){
		var window=me.up('window');
		window.close();
	},
	
	orgAddUser : function(me){
		this.settingWindow=me.up('window');
		var window=Ext.widget('orgAddUserWindow');
		window.show();
	},
	orgAddButton : function(me){
		var window=me.up('window');
		var orgName=window.down('textfield').getValue();
		var routeOrg = this.settingWindow.down('routeManageView').down('combobox[itemId=org]');
		var SpaceOrgStore = this.settingWindow.down('spaceManageView').down('combobox[itemId=org]').getStore();;
		var DomainOrgStore = this.settingWindow.down('domainManageView').down('combobox[itemId=org]').getStore();
		var errorTip = window.down('displayfield[itemId=orgExist]');
		var validate=true;
		Ext.Ajax.request({
			url : 'rest/org/checkOrgName',
			method : 'GET',
			async:false,
			params : {
				orgName : orgName
			},
			success : function(resp){
				var obj = Ext.JSON.decode(resp.responseText);
				validate=obj.data;
				if(obj.data==false){
					errorTip.setValue(cfWebLang.Bug.OrgNameExisted);
				    errorTip.setVisible(true);
	            }
			},
			failure : function(response){
				if(response.status=="401"){
			    	Ext.Msg.show({
			    	    title: cfWebLang.Util.Tip,
			    	    id:'firstWin',
			    	    msg: cfWebLang.Main.SessionOverdue,
			    	    width: 250,
			    	    buttons: Ext.MessageBox.OK,
			    	    fn: function(){  
			                parent.location.href = '/zwycf/login.html';    
			            },
			            cls:'overtimeWin'
			    	});
			    	//Ext.WindowManager.bringToFront ('firstWin');
			       /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){  
			            parent.location.href = '/zwycf/login.html';    
			        }); */
			       return;
			    }
				Ext.Msg.alert(cfWebLang.Util.Error,cfWebLang.CfWindow.InputAgain);
			}
		});
		if(!validate){
			return;
		}
		console.log(orgName);
		if(orgName){
			var orgGrid=this.settingWindow.down('grid[itemId=orgManagePanel]');
			var store=orgGrid.getStore();
			var quota=window.down('combobox[name=quota]').getValue();
			var data={
					name : orgName,
					quota:quota
				};
			Ext.Ajax.request({
				url : 'rest/org/add',
				method : 'POST',
				params :{
					orgName : orgName,
					quotaId:quota
				},
				success : function(resp){
					console.log("succe1ss");
					var flag =Ext.decode(resp.responseText).success;
					console.log(flag);
					var curOrg=Ext.fly('selectOrg');
					var orgStore = routeOrg.getStore();
					if(flag == true){
						store.add(data);
						orgStore.reload();
						SpaceOrgStore.reload();
						DomainOrgStore.reload();
						window.close();
						var obj=document.getElementById("selectOrg");
				    	obj.options.add(new Option(orgName,orgName));
					}
				},
				failure : function(resp){
					if(resp.status=="401"){
    	               Ext.Msg.show({
    	                 title: cfWebLang.Util.Tip,
    	                 id:'firstWin',
    	                 msg: cfWebLang.Main.SessionOverdue,
    	                 width: 250,
    	                 buttons: Ext.MessageBox.OK,
    	                 fn: function(){  
                            parent.location.href = '/zwycf/login.html';    
                         },
                         cls:'overtimeWin'
    	               });
                      return;
                   } 
                   if(resp.timedout){  
                      Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                         return;
                   }
					var error = Ext.JSON.decode(resp.responseText);
				    if(error.data!=null&&error.data.source==1){
				       Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				    }else{
				       Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				    }
				}
			});
		}
	},
	orgAddCancelButton : function(me){
		var window=me.up('window');
		window.close();
	},
	routerSpaceComboxChoose:function(me, value){
		var view = me.up('panel');
		var spaceCombox = view.down('combobox[itemId=space]');
		var naview=Ext.ComponentQuery.query('navView')[0];
		var currentOrgSpace=naview.getOrgSpace();
		var store = spaceCombox.getStore();
		store.removeAll();
		console.log("value:" + value);
		store.load({
			params : {
				orgName : value
			},
			callback:function(){
				if(value == currentOrgSpace.org)
					spaceCombox.setValue(currentOrgSpace.space);
				else{
					if(spaceCombox.getStore().data.items.length>0){
						spaceCombox.setValue(spaceCombox.getStore().data.items[0].data.name);
					}else{
						spaceCombox.setValue("");
					}
				}			
			}
		});
	},
	routeGridRender: function(me){
		var routeGrid = me.down('grid[itemId=routerManagePanel]');
		var store=routeGrid.getStore();
		var naview=Ext.ComponentQuery.query('navView')[0];
		var currentOrgSpace=naview.getOrgSpace();
		var comboboxOrg = me.down('combobox[itemId=org]');
		var comboboxSpace = me.down('combobox[itemId=space]');
		comboboxOrg.setValue(currentOrgSpace.org);
		comboboxSpace.setValue(currentOrgSpace.space);
		console.log(comboboxOrg.getValue());
		console.log(comboboxSpace.getValue());
		console.log("-----orgName:" + currentOrgSpace.org +"  spaceName:" + currentOrgSpace.space);
		store.load({
			params: {
				orgName:currentOrgSpace.org,
				spaceName:currentOrgSpace.space,
			},
			callback:function(){
//				comboboxOrg.setValue(currentOrgSpace.org);
//				comboboxSpace.setValue(currentOrgSpace.space);
//				this.routerChangeSpace;
			}
		});
	},
	routerChangeSpace: function(me, value){
		var view=me.up('panel');
		var grid=view.down('grid[itemId=routerManagePanel]');
		var orgCombox = view.down("combobox[itemId=org]");
		var orgValue = orgCombox.getValue();
		var store=grid.getStore();
		console.log("spacevalue:" + value);
		console.log("orgValue:" + orgValue);
		this.spaceName = value;
		this.orgName = orgValue;
		store.load({
			params : {
				orgName : orgValue,
				spaceName: value
			}
		});
		var isSpaceAuth = false;
		
		if(!isAdmin){		
		      	Ext.Ajax.request({
		      		url : 'rest/user/currentuserOrgRole',
		      		method : 'GET',
		      		params:{
		      			orgName:orgValue,
		      		},
		      		async : false,
		      		success : function(resp){
		      			var spaceArr = Ext.decode(resp.responseText).data,i;
		      			for(i = 0; i < spaceArr.length; ++i){
		      				if(spaceArr[i].spaceName == value&&(spaceArr[i].authType=='SpaceManager'||spaceArr[i].authType=='SpaceDeveloper')){
		      					isSpaceAuth = true;
		      					break;
		      				}
		      			}
		      		},
		      		failure : function(resp){
		      			if(resp.status=="401"){
    	                   Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                               parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                       } 
                       if(resp.timedout){  
                          Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                             return;
                       }
		      			var error = Ext.JSON.decode(resp.responseText);
				        if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				        }else{
				           Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				        }
		      		}
		      	});
		}
		grid.setVisible(true);
		grid.down("actioncolumn[itemId=editRouter]").hide();
  		grid.down("actioncolumn[itemId=deleteRoute]").hide();
  		view.down('button[itemId=addRoute]').setVisible(false);
		if(isAdmin || isSpaceAuth){// this is not right, just for test
      		grid.down("actioncolumn[itemId=editRouter]").show();
      		grid.down("actioncolumn[itemId=deleteRoute]").show();
      		view.down('button[itemId=addRoute]').setVisible(true);
      	}
	},
	routerAdd: function(me){
		this.settingWindow=me.up('window');
		var orgName = me.up('window').down('routeManageView').down('combobox[itemId=org]').getValue();
		var routeWindow = Ext.widget('routeAddWindow');
		routeWindow.show();
		var comboStore = routeWindow.down('combobox[itemId=inputDomainName]').getStore();
		comboStore.load({
			params:{
				orgName:orgName
			},
			callback:function(records){
				console.log(records);
			}
		});
	},
	routeEdit: function(me, record, rowIndex){
		
		console.log("me:" + me);
		console.log("can enter in when click the edit button!!");
		console.log(rowIndex);
		this.rowIndex = rowIndex;
//		var window = me.up('window');
		var windowPanel = me.up('panel').up('panel');
		this.settingWindow = windowPanel;
		var grid = windowPanel.down('grid[itemId=routerManagePanel]');
		this.oldApps = grid.getStore().getAt(rowIndex).get('apps');
		this.host = grid.getStore().getAt(rowIndex).get('host');
		this.domainName = grid.getStore().getAt(rowIndex).get('domain');
		console.log("domain: " + this.domainName + " host:" + this.host);
		console.log(this.oldApps);
		var orgName = windowPanel.down(
		'combobox[itemId=org]').getValue();
		console.log("test orgName :" + orgName);
		var spaceName = windowPanel.down(
		'combobox[itemId=space]').getValue();
		console.log("test spaceName :" + spaceName);
//		var apps = window.down('grid');
//		console.log(apps);
//		var editWindow = Ext.widget("routeAppEditView");
//		var itemSelector = editWindow.down('itemselector[itemId=appSelector]');
//		console.log("this orgName:" + this.orgName + " this spaceName:" + this.spaceName);
//		var store=itemSelector.getStore();
//		store.load({
//			params: {
//				orgName:this.orgName,
//				spaceName:this.spaceName,
//			}
//		});
//		editWindow.show();
	},
	afterRouteEditClose:function(me){
		console.log("only for window close!");
//		var itemSelector = me.down('itemselector[itemId=appSelector]');
		
	},
	editRouterSubmit:function(me){
		var window = me.up('window');
		var itemSelector = window.down('itemselector[itemId=appSelector]');
		var newApps=itemSelector.getValue();
		console.log(newApps);
		console.log(this.orgName + " " + this.spaceName + " " + this.host + " " + this.domainName + " " + newApps + " oldApps:" + this.oldApps);
		if(this.orgName && this.spaceName && this.host && this.domainName){
			var addApps = [],
				removeApps = [],
				i;
			for(i = 0; i < newApps.length; i++){
				if(this.oldApps.indexOf(newApps[i]) === -1){
					addApps.push(newApps[i]);
				}
			}
			for(i = 0; i <this.oldApps.length; i++){
				if(newApps.indexOf(this.oldApps[i]) === -1){
					removeApps.push(this.oldApps[i]);
				}
			}
			
			console.log("new apps:" + newApps + " old apps:" + this.oldApps);
			console.log("add apps:" + addApps  + " remove apps:" + removeApps);
			this.oldApps = newApps;
			for(i = 0; i < addApps.length; i ++){
				Ext.Ajax.request({
					url:'rest/route/map',
					method:'POST',
					params:{
						host:this.host,
						orgName:this.orgName,
						domainName:this.domainName,
						spaceName:this.spaceName,
						appName:addApps[i],
					},
					success:function(resp){
						console.log(resp);
						console.log("success");
					},
					faliure:function(resp){
						if(resp.status=="401"){
    	                   Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                               parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                        } 
                        if(resp.timedout){  
                           Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                              return;
                        }
						var error = Ext.JSON.decode(resp.responseText);
				        if(error.data!=null&&error.data.source==1){
				           Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				        }else{
				           Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				        }	 
					}
				})
			}
			for(i = 0; i < removeApps.length; i++){
				Ext.Ajax.request({
					url:'rest/route/unmap',
					method:'POST',
					params:{
						host:this.host,
						orgName:this.orgName,
						domainName:this.domainName,
						spaceName:this.spaceName,
						appName :removeApps[i],
					},
					success:function(resp){
						console.log(resp);
						console.log("success");
					},
					failure:function(resp){
						if(resp.status=="401"){
    	                   Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                               parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                        } 
                        if(resp.timedout){  
                           Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                              return;
                        }
						var error = Ext.JSON.decode(resp.responseText);
				        if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				        }else{
				           Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				        }	 
					}
				});
			}
		}
		var grid = this.settingWindow.down('grid[itemId=routerManagePanel]');
		var store = grid.getStore();
		store.getAt(this.rowIndex).set('apps', newApps);
//		store.remove(store.getAt(this.rowIndex));
//		srote.insert();
		window.close();
	},
	routeAddButton:function(me){
		var window=me.up('window');
		console.log(window);
		var host=window.down('textfield[itemId=inputHostName]').getValue();
		console.log("add host name:" + host);
		var domainName = window.down('textfield[itemId=inputDomainName]').getValue();
		console.log("add domain name" + domainName);
		var orgName=this.settingWindow.down('routeManageView').down('combobox[itemId=org]').getValue();
		console.log("add org Name " + orgName);
		var spaceName = this.settingWindow.down('routeManageView').down('combobox[itemId=space]').getValue();
		var validate=true;
		Ext.Ajax.request({
			url: 'rest/route/checkRouteName',
			method: 'GET',
			async:false,
			params:{
				host:host,
				orgName:orgName,
				domain:domainName,
			},
			success:function(resp){
				var obj = Ext.JSON.decode(resp.responseText);
				validate=obj.data;
				if(!obj.data){
					window.down('displayfield[itemId=errorRouteTip]').setValue(cfWebLang.SettingWindow.RouteExit);
					window.down('displayfield[itemId=errorRouteTip]').setVisible(true);
				}
			},
			failure:function(response){
				if(response.status=="401"){
			    	Ext.Msg.show({
			    	    title: cfWebLang.Util.Tip,
			    	    id:'firstWin',
			    	    msg: cfWebLang.Main.SessionOverdue,
			    	    width: 250,
			    	    buttons: Ext.MessageBox.OK,
			    	    fn: function(){  
			                parent.location.href = '/zwycf/login.html';    
			            },
			            cls:'overtimeWin'
			    	});
			    	//Ext.WindowManager.bringToFront ('firstWin');
			       /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){  
			            parent.location.href = '/zwycf/login.html';    
			        }); */
			       return;
			    }
				Ext.Msg.alert(cfWebLang.Util.Error,cfWebLang.CfWindow.InputAgain);
			}
		});
		if(!validate){
			return;
		}
		if(host && domainName){
			var routeGrid = this.settingWindow.down('grid[itemId=routerManagePanel]');
			var routeStore = routeGrid.getStore();
			var data={
					host:host,
					domain:domainName
			};
			routeStore.add(data);
			window.close();
			Ext.Ajax.request({
				url: 'rest/route/add',
				method: 'POST',
				params:{
					host:host,
					orgName:orgName,
					domainName:domainName,
					spaceName:spaceName
				},
				success:function(resp){
					console.log(resp);
					console.log("success");
					routeOper = true;
				},
				failure:function(resp){
					if(resp.status=="401"){
    	                Ext.Msg.show({
    	                   title: cfWebLang.Util.Tip,
    	                   id:'firstWin',
    	                   msg: cfWebLang.Main.SessionOverdue,
    	                   width: 250,
    	                   buttons: Ext.MessageBox.OK,
    	                   fn: function(){  
                              parent.location.href = '/zwycf/login.html';    
                           },
                           cls:'overtimeWin'
    	                });
                        return;
                     } 
                    if(resp.timedout){  
                        Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                            return;
                    }
					var error = Ext.JSON.decode(resp.responseText);
				    if(error.data!=null&&error.data.source==1){
					     Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				    }else{
					     Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				    }
				}
			});
		}
	},
	spaceGridRender : function(me){
		console.log(me);
		console.log("me");
		var naview=Ext.ComponentQuery.query('navView')[0];
		var currentOrgSpace=naview.getOrgSpace();
		var combobox = me.down('combobox[itemId=org]');
		var button=me.down('button[itemId=addSpaceUser]');
		console.log(button);
//		var button=me.down('button');
//		button.setVisible(false);
		var spaceGrid=me.down('grid[itemId=spaceManagePanel]');
		var store=spaceGrid.getStore();
		var me = this;
		store.load({
			params:{
				orgName:currentOrgSpace.org
			},
			callback:function(){
				combobox.setValue(currentOrgSpace.org);
				me.spaceChangeOrg(combobox,currentOrgSpace.org);
			}
		});
	},
	spaceAddUser : function(me){
		this.settingWindow=me.up('window');
		var window=Ext.widget('spaceAddUserWindow');
		window.show();
//		console.log("add");
//		console.log(me);
//		var panel=me.up('panel[itemId=spaceManageWindow]');
//		console.log(panel);
//		var orgName=panel.down('combobox').getValue();
//		console.log(orgName);
//		var grid=panel.down('grid[itemId=spaceManagePanel]');
//		console.log(grid);
//		var store=grid.getStore();
//		console.log(store);
//		var rec=({
//			name : '',
//			'organization.name' : orgName
//		});
//		store.add(rec);
//		console.log(grid);
//		console.log(store);
//		var rindex=store.data.length-1;
//		console.log(store.data.length);
//		var obj=grid.down('textfield[itemId=""]');
//		console.log("obj");
//		console.log(obj);
	},
	spaceChangeOrg : function(me,value){
		console.log(me);
		console.log(value);
		var view=me.up('panel');
		console.log(view);
		var grid=view.down('grid[itemId=spaceManagePanel]');
		console.log(grid);
		var store=grid.getStore();
		console.log(store);
		store.load({
			url : 'rest/space/list',
			params : {
				orgName : value
			}
		});
		grid.setVisible(true);
		var button=view.down('button[itemId=addSpaceUser]');
		button.setVisible(true);
		var visibleFlag = false;
		if(isAdmin == 0){
			button.setVisible(false);
		}else{
			button.setVisible(true);
		}
		if(isAdmin == false){
			var length = userRoles.length;
			console.log("length =" +length);
			var i=0;
			for(;i<length;i++){
				if(userRoles[i].orgName == value && userRoles[i].authType == "OrgManager"){
					visibleFlag = true;
				}
			}
			if(visibleFlag == true){
				button.setVisible(true);
			}else if(visibleFlag == false){
				button.setVisible(false);
			}
		}
//		Ext.Ajax.request({
//			url : 'rest/user/currentuserRole',
//			method : 'GET',
//			async : false,
//			success : function(resp){
//				var data=Ext.decode(resp.responseText).data;
//				console.log(data);
//				var length = data.length;
//				console.log("length = "+length);
//				var i = 0;
//				if(data[i].orgName == value && data[i].authType == "OrgManager")
//			},
//			failure : function(resp){
//				
//			}
//		})
	},
	spaceAddButton : function(me){
		var window=me.up('window');
		var spaceName=window.down('textfield').getValue();
		var errorTip = window.down('displayfield');
		console.log(spaceName);
		var currentRouteOrg = this.settingWindow.down('routeManageView').down('combobox[itemId=org]').getValue();
		var routeSpace = this.settingWindow.down('routeManageView').down('combobox[itemId=space]');
		var orgName=this.settingWindow.down('combobox').getValue();
		console.log(orgName);
		console.log(spaceName);
		var validate=true;
		Ext.Ajax.request({
			url:'rest/space/checkSpaceName',
		    method:'GET',
		    async:false,
		    params:{
				orgName : orgName,
				spaceName : spaceName
			},
			success:function(resp){
				var obj = Ext.JSON.decode(resp.responseText);
				validate=obj.data;
				if(obj.data==false){
					errorTip.setValue(cfWebLang.Bug.SpaceNameExisted);
					errorTip.setVisible(true);
				}
			},
			failure:function(){
				Ext.Msg.alert(cfWebLang.Util.Error,cfWebLang.CfWindow.InputAgain);
			}
		});
		if(!validate){
			return;
		}
		if(spaceName){
			var spaceGrid=this.settingWindow.down('grid[itemId=spaceManagePanel]');
			var store=spaceGrid.getStore();
			var data={
				name : spaceName,
				'organization.name' :orgName
			};
			Ext.Ajax.request({
				url : 'rest/space/add',
				method : 'POST',
				params :{
					orgName : orgName,
					spaceName : spaceName
				},
				success : function(resp){
					console.log(resp);
					store.load({
						url : 'rest/space/list',
						params :{
							orgName : orgName
						},
						callback:function(records){
							console.log(records);
							if(Ext.fly('selectOrg').getValue()==orgName){
							    var obj=document.getElementById("selectSpace");
							    var space = records[records.length-1].data.name;
				    	        obj.options.add(new Option(space,space));
							}
						}
					});
					var flag =Ext.decode(resp.responseText).success;
					console.log(flag);
					var spaceStore = routeSpace.getStore();
					if(flag == true){
						spaceStore.reload();
						window.close();
					}
				},
				failure : function(resp){
					if(resp.status=="401"){
    	                Ext.Msg.show({
    	                   title: cfWebLang.Util.Tip,
    	                   id:'firstWin',
    	                   msg: cfWebLang.Main.SessionOverdue,
    	                   width: 250,
    	                   buttons: Ext.MessageBox.OK,
    	                   fn: function(){  
                              parent.location.href = '/zwycf/login.html';    
                           },
                           cls:'overtimeWin'
    	                });
                        return;
                     } 
                    if(resp.timedout){  
                        Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                            return;
                    }
					var error = Ext.JSON.decode(resp.responseText);
				    if(error.data!=null&&error.data.source==1){
				       Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				    }else{
				        Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
				    }
				}
			});
		}
	},
	spaceCancelButton : function(me){
		var window=me.up('window');
		window.close();
	},
	userGridRender : function(me){
		var userGrid=me.down('grid[itemId=userManagePanel]');
		var addButton=me.down('button');
		console.log(userGrid);
		console.log(addButton);
        if(isAdmin == 0){
			userGrid.setVisible(false);
			addButton.setVisible(false);
		}
		var store=userGrid.getStore();
		store.load();
	},
	userAddUser : function(me){
		this.settingWindow=me.up('window');
		var window=Ext.widget('userAddUser');
		window.show();
		console.log("me");
		console.log(me);
		console.log(this.settingWindow);
	},
	userAddButton : function(me){
		var window=me.up('window');
		var userName=window.down('textfield[itemId=inputUserName]').getValue();
		var userPass=window.down('textfield[itemId=inputPassword]').getValue();
		var isTipHidden = window.down('displayfield[itemId=errorUserTip]').isHidden();
		var isPassHidden = window.down('displayfield[itemId=errorPasswordTip]').isHidden();
		if(isTipHidden==false){
			return false;
		}
		if(isPassHidden==false){
			return;
		}
		if(userName&&userPass){
			var userGrid=this.settingWindow.down('grid[itemId=userManagePanel]');
			var store=userGrid.getStore();
			/*var data={
				userName: userName,
				userPass: userPass
			};
			store.add(data);*/
			window.close();
			console.log('user');
			Ext.Ajax.request({
				url : 'rest/user/add',
				method : 'POST',
				params : {
					userName : userName,
					userPass : userPass
				},
				success : function(){
					store.reload();
					console.log('userSuccess');
				},
				failure : function(resp){
					if(resp.status=="401"){
    	                Ext.Msg.show({
    	                   title: cfWebLang.Util.Tip,
    	                   id:'firstWin',
    	                   msg: cfWebLang.Main.SessionOverdue,
    	                   width: 250,
    	                   buttons: Ext.MessageBox.OK,
    	                   fn: function(){  
                              parent.location.href = '/zwycf/login.html';    
                           },
                           cls:'overtimeWin'
    	                });
                        return;
                     } 
                    if(resp.timedout){  
                        Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                            return;
                    }
					var error = Ext.JSON.decode(resp.responseText);
				    if(error.data!=null&&error.data.source==1){
				       Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				    }else{
				        Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
			     	}
				}
			});
		}
	},
	userCancelButton : function(me){
		var window=me.up('window');
		window.close();
	},
	domainGridRender : function(me){
		var domainGrid=me.down('grid[itemId=domainManagePanel]');
		var store=domainGrid.getStore();
		console.log("domain");
		console.log(me);
		var naview=Ext.ComponentQuery.query('navView')[0];
		var currentOrgSpace=naview.getOrgSpace();
		var combobox = me.down('combobox[itemId=org]');
		var me = this;
		store.load({
			callback:function(){
				combobox.setValue(currentOrgSpace.org);
				me.domainChangeOrg;
			}
		});
	},
	domainAddUser : function(me){
		this.settingWindow=me.up('window');
		var win = me.up('domainManageView');
		console.log(win);
		var window =Ext.widget('domainAddUserWindow');
		var combobox = window.down('combobox[itemId=property]') ;
		var orgName=Ext.ComponentQuery.query('domainManageView combobox')[0].getValue();
		window.orgName=orgName;
		console.log(window);
		var orgField = window.down('displayfield[itemId=whichOrg]');
		if(win.isAdmin==1){
			combobox.store = Ext.create('Ext.data.Store', {
				fields : ['value', 'text'],
				data : [{value : 'shared',text : 'shared'},
				        {value : 'private',text : 'owned'}]});
			combobox.setValue('owned');
		}
		else{
			combobox.store = Ext.create('Ext.data.Store', {
				fields : ['value', 'text'],
				data : [{value : 'private',text : 'owned'}]});
			combobox.setValue('owned');
		}
		window.show();console.log(orgField)
	},

	domainChangeOrg : function(me,value){
		console.log(me);
		console.log(value);
		var view=me.up('panel');
		console.log(view);
		var grid=view.down('grid[itemId=domainManagePanel]');
		console.log(grid);
		var store=grid.getStore();
		console.log(store);
		store.load({
			url : 'rest/domain/list',
			params : {
				orgName : value
			}
		});
		grid.setVisible(true);
	},
	
	domainChangeProperty : function(me,value){
		console.log(me);
		console.log(value);
		var window=me.up('window');
		console.log(window);
		var orgField=window.down('displayfield[itemId=whichOrg]');
		orgProperty=window.down('combobox[itemId=property]').getValue();
		if(orgProperty == 'shared')
			orgField.setValue("all");
		else
			orgField.setValue(window.orgName);
	},
	
	domainAddButton : function(me){
		var window=me.up('window');
		var domainName=window.down('textfield').getValue();
		var orgName=this.settingWindow.down('combobox').getValue();
		var orgName=window.orgName;
		var orgProperty=window.down('combobox[itemId=property]').getValue();
		console.log(orgProperty);
		var isShared = false;
		if(orgProperty=='shared'){
				isShared=true;
		}
		var isTipHidden = window.down('displayfield[itemId=errorDomainTip]').isHidden();
		var domainTip = window.down('displayfield[itemId=errorDomainTip]');
		var isCorrect = true;
		if(isTipHidden==false){
			return false;
		}
		var reg=/\./g;
	    if(domainName.match(reg)==null){
		    domainTip.setValue(cfWebLang.SettingWindow.DomainFormat);
			domainTip.setVisible(true);
			return;
		}
		Ext.Ajax.request({
			url:'rest/domain/checkDomainName',
			method:'GET',
			async:false,
			params:{
				domainName:domainName,
				isShared:isShared
			},
			success:function(res){
				var obj = Ext.JSON.decode(res.responseText);
				isCorrect=obj.data;
				if(obj.data==false){
					domainTip.setValue(cfWebLang.SettingWindow.DomainExit);
					domainTip.setVisible(true);
				}
			},
			failure:function(res){
				if(response.status=="401"){
			    	Ext.Msg.show({
			    	    title: cfWebLang.Util.Tip,
			    	    id:'firstWin',
			    	    msg: cfWebLang.Main.SessionOverdue,
			    	    width: 250,
			    	    buttons: Ext.MessageBox.OK,
			    	    fn: function(){  
			                parent.location.href = '/zwycf/login.html';    
			            },
			            cls:'overtimeWin'
			    	});
			    	//Ext.WindowManager.bringToFront ('firstWin');
			       /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){  
			            parent.location.href = '/zwycf/login.html';    
			        }); */
			       return;
			    }
				Ext.Msg.alert(cfWebLang.Util.Error,cfWebLang.CfWindow.InputAgain);
			}
		});
		if(!isCorrect){
			return;
		}
		if(domainName){
			var domainGrid=this.settingWindow.down('grid[itemId=domainManagePanel]');
			var store=domainGrid.getStore();
			if(orgProperty=='shared'){
				var data={
						name : domainName,
						status : orgProperty
				};
				store.add(data);
				window.close();
				Ext.Ajax.request({
					url : 'rest/domain/add-shared',
					method : 'POST',
					params :{
						domainName : domainName
					},
					success : function(resp){
						console.log(resp);
						console.log("success");
					},
					failure : function(resp){
						if(resp.status=="401"){
    	                   Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                                parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                   });
                           return;
                       } 
                       if(resp.timedout){  
                           Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                             return;
                       }
                       var error = Ext.JSON.decode(resp.responseText);
				       if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				       }else{
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
			     	   }
					}
				})
			}
			if(orgProperty=='owned'){
				var data={
						name : domainName,
						status : orgProperty,
						whichOrg : orgName
				};
				store.add(data);
				window.close();
				Ext.Ajax.request({
					url : 'rest/domain/add-private',
					method : 'POST',
					params :{
						domainName : domainName ,
						orgName : orgName
					},
					success : function(resp){
						console.log(resp);
						console.log("success");
					},
					failure : function(resp){
						if(resp.status=="401"){
    	                  Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                                parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                       } 
                       if(resp.timedout){  
                          Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                              return;
                       }
                       var error = Ext.JSON.decode(resp.responseText);
				       if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				       }else{
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
			     	   }
				   }
				})
			}
		}
	},
	domainCancelButton : function(me){
		var window=me.up('window');
		window.close();
	},
	orgEditConfirmButton : function(me){
		var window = me.up('window');
		var routeOrg = window.routeView.down('combobox[itemId=org]').getValue();
	    var routeOrgStore =window.routeView.down('combobox[itemId=org]').getStore();
	    var spaceOrg = window.spaceView.down('combobox[itemId=org]').getValue();
	    var domainOrg = window.domainView.down('combobox[itemId=org]').getValue();
		var errorTip = window.down('displayfield');
		console.log(window.rindexFlag);
		console.log(window.component);
		var grid = window.component;
		var store =grid.getStore();
		console.log(store);
		var text = window.down('textfield');
		var textValue = text.getValue();
		console.log(textValue);
		var rindex = window.rindexFlag;
		var addflag = true;
		Ext.Ajax.request({
			url : 'rest/org/checkOrgName',
			method : 'GET',
			async:false,
			params : {
				orgName : textValue,
				guid:store.getAt(rindex).get('guid')
			},
			success : function(resp){
				var obj = Ext.JSON.decode(resp.responseText);
				addflag = obj.data;
				if(obj.data==false){
					errorTip.setValue(cfWebLang.Bug.OrgNameExisted);
					errorTip.setVisible(true);
				}
			},
			failure : function(response){
				if(response.status=="401"){
			    	Ext.Msg.show({
			    	    title: cfWebLang.Util.Tip,
			    	    id:'firstWin',
			    	    msg: cfWebLang.Main.SessionOverdue,
			    	    width: 250,
			    	    buttons: Ext.MessageBox.OK,
			    	    fn: function(){  
			                parent.location.href = '/zwycf/login.html';    
			            },
			            cls:'overtimeWin'
			    	});
			    	//Ext.WindowManager.bringToFront ('firstWin');
			       /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){  
			            parent.location.href = '/zwycf/login.html';    
			        }); */
			       return;
			    }
				Ext.Msg.alert(cfWebLang.Util.Error,cfWebLang.CfWindow.InputAgain);
			}
		});
		if(!addflag){
			return;
		}
		
		var quota=window.down('combobox[name=quota]').getValue();
		if (textValue){
	    	var record=store.getAt(rindex);
	    	var orgName=record.data.name;
	    	var newName=textValue;
	    	Ext.Ajax.request({
	    		url : 'rest/org/update',
	    		method : 'POST',
	    		params :{
	    			orgName : orgName,
	    			newName : newName,
	    			quotaId : quota
	    		},
	    		success : function(resp){
	    			if(window.quota!=quota){
	    				routeOper=true;
	    			}
	    			var nameExistFlag = false;
	    			var i=0;
	    			var length=store.data.length;
	    			console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!");
	    			console.log(store.data.length);
	    			for(i=0;i<length;i++){
	    				if(i!= rindex){
	    					if(textValue == store.getAt(i).data.name){
	    						nameExistFlag = true;
	    					}
	    				}
	    			}
	    			if(nameExistFlag == true){
	    				errorTip.setVisible(true);
	    			}else{
	    				store.reload();
	    				routeOrgStore.load({
	    					callback:function(record){
	    						if(routeOrg==orgName){
	    					       if(routeOrgStore.data.length>0){
	                			       window.routeView.down('combobox[itemId=org]').setValue(newName);
	                			       if(domainOrg==orgName){
	                			       	    window.domainView.down('combobox[itemId=org]').setValue(newName);
	                			       }
	                			       if(spaceOrg==orgName){
	                			       	     window.spaceView.down('combobox[itemId=org]').setValue(newName);
	                			       }
	                		       }else{
	                			       window.routeView.down('combobox[itemId=org]').setValue('');
	                		       }
	    				        }
	    					}
	    				});
	    				window.close();
	    			}
	    			for(var j=0;j<userRoles.length;j++){
		      			if(userRoles[j].orgName == orgName){
		      				userRoles[j].orgName=newName;
		      			}
		      		}
	    			var curOrg=Ext.fly('selectOrg');
	    			if(curOrg.getValue().trim()==orgName.trim()){
	    				var obj=document.getElementById("selectOrg");
	    				obj.options[obj.selectedIndex].innerHTML=newName;
	    				obj.options[obj.selectedIndex].value=newName;
	    				Ext.getCmp('navView').orgOnChange(Ext.fly('selectSpace').getValue(),true);
	    			}else{
				    	var obj=document.getElementById("selectOrg");
				        for(var i=0;i<obj.length;i++){
				    	    if(orgName.trim()==obj.options[i].value){
				    	    	obj.options.remove(i);
				    		    obj.options.add(new Option(newName,newName));
				    		}
				        }
				    }
	    			
	    			
	    		},
	    		failure : function(resp){
	    			if(resp.status=="401"){
    	                  Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                                parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                       } 
                       if(resp.timedout){  
                          Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                              return;
                       }
                       var error = Ext.JSON.decode(resp.responseText);
				       if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				       }else{
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
			     	   }
	    		}
	    	});
	    }
		
		
		
		
	},
	orgEditCancelButton : function(me){
		console.log(me);
		var window = me.up('window');
		window.close();
	},
	spaceEditConfirmButton : function(me){
		var windowEdit=me.up('window');
		var errorTip = windowEdit.down('displayfield');
		var routeOrg = windowEdit.routePanel.down('combobox[itemId=org]').getValue();
	    var routeSpace = windowEdit.routePanel.down('combobox[itemId=space]').getValue();
	    var routeSpaceStore = windowEdit.routePanel.down('combobox[itemId=space]').getStore();
		console.log(windowEdit.rindexFlag);
		console.log(windowEdit.component);
		var grid = windowEdit.component;
		var window=grid.up('panel[itemId=spaceManageWindow]');
	    var orgName = window.down('combobox').getValue();
	    console.log(orgName);
		var store =grid.getStore();
		console.log(store);
		var text = windowEdit.down('textfield');
		var textValue = text.getValue();
		console.log(textValue);
		var rindex = windowEdit.rindexFlag;
		var validate=true;
		Ext.Ajax.request({
			url:'rest/space/checkSpaceName',
		    method:'GET',
		    async:false,
		    params:{
				orgName : orgName,
				spaceName : textValue
			},
			success:function(resp){
				var obj = Ext.JSON.decode(resp.responseText);
				validate=obj.data;
				if(obj.data==false){
					errorTip.setValue(cfWebLang.Bug.SpaceNameExisted);
					errorTip.setVisible(true);
				}
			},
			failure:function(){
				Ext.Msg.alert(cfWebLang.Util.Error,cfWebLang.CfWindow.InputAgain);
			}
		});
		if(!validate){
			return;
		}
		if (textValue){
	    	var record=store.getAt(rindex);
	    	var spaceName=record.data.name;
	    	var newName=textValue;
	    	console.log(record.data.name);
	    	console.log(textValue);
	    	console.log(me);
	    	Ext.Ajax.request({
	    		url : 'rest/space/rename',
	    		method : 'POST',
	    		params :{
	    			orgName : orgName,
	    			spaceName : spaceName,
	    			newName : newName
	    		},
	    		success : function(resp){
	    			console.log("rename success");
	    			
	    			var nameExistFlag = false;
	    			var i=0;
	    			var length=store.data.length;
	    			console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!");
	    			console.log(store.data.length);
	    			console.log("!!!!!!!!!!!!!!!!!!!!!!");
	    			for(i=0;i<length;i++){
	    				if(i!= rindex){
	    					if(textValue== store.getAt(i).data.name){
	    						nameExistFlag = true;
	    					}
	    				}
	    			}
	    			if(nameExistFlag == true){
	    				errorTip.setValue(cfWebLang.Bug.SpaceNameExisted);
	    				errorTip.setVisible(false);
	    			}else{
	    				routeSpaceStore.reload();
	                	if(orgName==routeOrg&&routeSpace==spaceName){
	                		if(routeSpaceStore.data.length>0){
	                			windowEdit.routePanel.down('combobox[itemId=space]').setValue(routeSpaceStore.data.items[0].data.name);
	                		}else{
	                			windowEdit.routePanel.down('combobox[itemId=space]').setValue('');
	                		}
	                	}
	    				windowEdit.close();
	    			}
	    			
	    			
	    			
	    			store.load({
	    				url : 'rest/space/list',
	    				params :{
	    					orgName : orgName
	    				}
	    			});
	    			for(var j=0;j<userRoles.length;j++){
		      			if(userRoles[j].spaceName == spaceName){
		      				userRoles[j].spaceName=newName;
		      			}
		      		}
	    			var curSpace=Ext.fly('selectSpace');
	    			console.log(curSpace.getValue()+'  '+spaceName+'  '+newName);
	    			if(curSpace.getValue().trim()==spaceName.trim()){
	    				var obj=document.getElementById("selectSpace");
	    				obj.options[obj.selectedIndex].innerHTML=newName;
	    				obj.options[obj.selectedIndex].value=newName;
	    				Ext.getCmp('navView').spaceOnChange();
	    			}else{
				    	var obj=document.getElementById("selectSpace");
				        for(var i=0;i<obj.length;i++){
				    	    if(spaceName.trim()==obj.options[i].value){
				    	    	obj.options.remove(i);
				    		    obj.options.add(new Option(newName,newName));
				    		}
				        }
				    }
	    		},
	    		failure : function(resp){
	    			if(resp.status=="401"){
    	                  Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                                parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                       } 
                       if(resp.timedout){  
                          Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                              return;
                       }
                       var error = Ext.JSON.decode(resp.responseText);
				       if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				       }else{
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
			     	   }
	    		}
	    	})
	    }
	},
	spaceEditCancelButton : function(me){
		console.log(me);
		var window = me.up('window');
		window.close();
	},
	
	routeCancelButton : function(me){
		var win = me.up('window');
		win.close();
	},
	
	editRouterCancel : function(me){
		var win = me.up('window');
		win.close();
	},
	
	renderWin:function(me){
		Ext.Ajax.request({
	           url : 'rest/user/isAdmin',
	           method :  'GET',
	           aysnc:false,
	           success : function(resp){
	     	      isAdmin=Ext.decode(resp.responseText).isAdmin;
	     	      console.log(isAdmin);
	         }
	      });
	        if(isAdmin==false){
	        	Ext.Ajax.request({
	      			url : 'rest/user/currentuserRole',
	      			method : 'GET',
	      			success : function(resp){
	      				userRoles=Ext.decode(resp.responseText).data;
	      				console.log(userRoles);
	      			}
	           });
	        }
	},
	
	routeFresh : function(me){
		if(routeOper==true && Ext.getCmp('tab_home')!=null){
			var routeUsed = Ext.getCmp('tab_home').down('collapsibleBlock').down('ringChart[itemId=routeUsed]').store;
		    var serviceUsed = Ext.getCmp('tab_home').down('collapsibleBlock').down('ringChart[itemId=serviceUsed]').store;
		    var appStatus = Ext.getCmp('tab_home').down('collapsibleBlock').down('ringChart[itemId=appStatus]').store;
		    for(var i = 0;i<appStatus.data.length;i++){
				   	   console.log(appStatus.data.items[i]);
				   }
	    	var memoryUsed = Ext.getCmp('tab_home').down('collapsibleBlock').down('ringChart[itemId=memoryUsed]').store;
			Ext.Ajax.request({
		        url : 'rest/info/basicInfo',
		        method : 'GET',
		        success : function(resp){
			       dashData = Ext.JSON.decode(resp.responseText);
				   var data = dashData;
				   routeUsed.add({itemId : '1',itemName : cfWebLang.HomeTabView.used,itemCount : data.routesNum,total : data.routesAll});
				   routeUsed.removeAt(0);
				   serviceUsed.add({itemId : '1',itemName : cfWebLang.HomeTabView.used,itemCount : data.serviceNum,total : data.serviceAll});
				   serviceUsed.removeAt(0);
				   if(data.memoryAll<1024){
						total=data.memoryAll;
						Ext.getCmp('tab_home').down('collapsibleBlock').down('ringChart[itemId=memoryUsed]').unit='M';
					}else{
						total=data.memoryAll/1024;
						Ext.getCmp('tab_home').down('collapsibleBlock').down('ringChart[itemId=memoryUsed]').unit='G';
					}
					
					if(data.memoryUsed<1024){
						count=data.memoryUsed;
					}else{
						count=data.memoryUsed/1024;
					}
					
				   memoryUsed.add({itemId : '1',itemName :cfWebLang.HomeTabView.used,itemCount : count.toFixed(2),total : total});
			       memoryUsed.removeAt(0);
		        },
		        failure : function(resp){
	    			if(resp.status=="401"){
    	                  Ext.Msg.show({
    	                     title: cfWebLang.Util.Tip,
    	                     id:'firstWin',
    	                     msg: cfWebLang.Main.SessionOverdue,
    	                     width: 250,
    	                     buttons: Ext.MessageBox.OK,
    	                     fn: function(){  
                                parent.location.href = '/zwycf/login.html';    
                             },
                             cls:'overtimeWin'
    	                  });
                          return;
                       } 
                       if(resp.timedout){  
                          Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.global.timeout);  
                              return;
                       }
                       var error = Ext.JSON.decode(resp.responseText);
				       if(error.data!=null&&error.data.source==1){
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry,error.data.message);
				       }else{
				          Ext.MessageBox.alert(cfWebLang.ErrorSource.app,cfWebLang.Error.SystemError);
			     	   }
	    		}
	        });
	        routeOper==false;
		}
	}
});
